from django.db.models import Count, OuterRef, Q, Subquery
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.chat.serializers import ChatMessageModelSerializer, RecentContactsUserModelSerializer, \
    SystemMessageModelSerializer
from apps.users.models import User, ChatMessage
from utils.paginations import LargePageNum


class RecentContactsUsersListView(ListAPIView):
    queryset = User.objects.all()
    pagination_class = LargePageNum
    serializer_class = RecentContactsUserModelSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        receivers = request.user.sent_message.all().values('receiver').distinct()
        subquery = ChatMessage.objects.filter(Q(sender=OuterRef('pk')) | Q(receiver=OuterRef('pk')),
                                              is_system=False).order_by(
            '-create_time')
        queryset = queryset.filter(id__in=receivers).annotate(
            newest_message=Subquery(subquery.values('message')[:1]),
            newest_create_time=Subquery(subquery.values('create_time')[:1]),
            unread_message=Count('sent_message',
                                 filter=Q(sent_message__read=False, sent_message__receiver_id=request.user.id,
                                          sent_message__is_system=False)),
        ).order_by('-newest_create_time')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class HistoryMessageListView(ListAPIView):
    queryset = ChatMessage.objects.filter(is_system=False)
    pagination_class = LargePageNum
    serializer_class = ChatMessageModelSerializer

    def list(self, request, *args, **kwargs):
        target = kwargs.get('target', None)
        if not target:
            return JsonResponse({'message': '参数错误'})
        queryset = self.filter_queryset(self.get_queryset())
        queryset = queryset.filter(Q(sender_id=request.user.id, receiver_id=target) |
                                   Q(sender_id=target, receiver_id=request.user.id)).order_by('-create_time')
        page = self.paginate_queryset(queryset)
        rows = self.queryset.filter(sender_id=target, receiver_id=request.user.id,
                                    id__in=[msg.id for msg in page], read=False).update(read=True)
        print(rows)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class SystemMessageListView(ListAPIView):
    queryset = ChatMessage.objects.filter(is_system=True)
    pagination_class = LargePageNum
    serializer_class = SystemMessageModelSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = queryset.filter(receiver_id=request.user.id).order_by('-create_time')
        page = self.paginate_queryset(queryset)
        rows = self.queryset.filter(id__in=[msg.id for msg in page], read=False).update(read=True)
        print(rows)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class SystemMessageUnreadCountView(APIView):
    def get(self, request):
        count = ChatMessage.objects.filter(is_system=True, read=False).count()
        return JsonResponse({'message': 'OK', 'count': count})
